<?php

namespace App\Http\Controllers\Api;

use App\Models\Station;
use Illuminate\Http\Request;
use App\Http\Requests\StationRequest;

class StationController extends Controller
{

    // 新增加油站
    public function create(StationRequest $request){
        Station::create($request->all());

        return $this->message('新增成功');
    }

    // 修改加油站信息
    public function edit(StationRequest $request){
        $station = Station::withTrashed()->findOrFail($request->id);
        $station->update($request->all());

        return $this->message('修改成功');
    }

    // 获取城市列表
    public function citylist(){
        $citys = Station::groupBy('city')->pluck('city');
        $citys = array_values(array_filter($citys->toArray()));

        return $this->success($citys);
    }

    //  查看单个加油站
    public function detail(StationRequest $request){
        $id = $request->get('id');
        if ($request->get('all'))
            // 包括下架门店
            $station = Station::withTrashed()->findOrFail($id);
        else
            $station = Station::findOrFail($id);

        return $this->success($station);   
    }

    //  搜索加油站
    public function search(Request $request){
        $code_id = $request->code_id;
        $city = $request->city;
        if ($city) {
            $station = Station::withTrashed()->where('city', $city)->paginate(10);
        }
        if ($code_id) {
            $station = Station::withTrashed()->where('code_id', $code_id)->paginate(10);
        }
        return $this->success($station);   
    }

    //返回加油站列表 10篇为一页
    public function list(Request $request){
        // 获取所有，包括软删除
        if($request->all)
            $stationList = Station::withTrashed()->orderBy('created_at', 'desc')->paginate(10);
        else
            $stationList = Station::orderBy('created_at', 'desc')->paginate(10);

        return $this->success($stationList);
    }

    // 返回当前城市加油站列表
    public function currentCityList(StationRequest $request){
        // 是否需要根据距离排序，还是前端计算
        $stationList = Station::whereCity($request->city)->orderBy('created_at')->get();

        return $this->success($stationList);
    }

    // 下架加油站
    public function delete(StationRequest $request){
        Station::withTrashed()->findOrFail($request->id)->delete();
        return $this->message('加油站下架成功');
    }

    // 恢复下架加油站
    public function restored(StationRequest $request){
        Station::withTrashed()->findOrFail($request->id)->restore();
        return $this->message('加油站恢复成功');
    }

    // 真删除加油站
    public function reallyDelete(StationRequest $request){
        Station::findOrFail($request->id)->forceDelete();
        return $this->success('加油站删除成功');
    }
}
